package com.mtiiot.fstcpserver.email;

import com.mtiiot.fstcpserver.base.BaseService;
import com.mtiiot.fscore.bean.MetadataInfo;
import com.mtiiot.fscore.bean.elasticsearch.metadata.EmailMetadata;
import com.mtiiot.fscore.bean.email.MailAttachmentBean;
import com.mtiiot.fscore.inter1.EmailService1;
import com.mtiiot.fscore.utils.RequestType;
import com.mtiiot.fstcpserver.utils.Constants;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * Created by Administrator on 16-8-23.
 */
public class EmailServiceImpl1 extends BaseService implements EmailService1 {
    private static final Logger logger = LogManager.getLogger(EmailServiceImpl1.class);

    /**
     * @param toAddrs 收件人地址邮箱列表
     * @param topic   邮件主题
     * @param text    邮件内容
     * @return
     */
    @Override
    public boolean sendEmailByText(MetadataInfo metadataInfo, String[] toAddrs, String topic, String text) {
        try {
            checkMetadata(metadataInfo);
            //1.发送邮件
            Properties prop = new Properties();
            //prop.setProperty("mail.smtp.auth","true");
            Session session = Session.getInstance(prop, null);
            session.setDebug(false);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(getFsConfig().getFromUsername()));
            message.setText(text);
            message.setSubject(topic);

            InternetAddress[] addresses = new InternetAddress[toAddrs.length];
            for (int i = 0; i < toAddrs.length; i++) {
                addresses[i] = new InternetAddress(toAddrs[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addresses);
            Transport transport = session.getTransport("smtp");
            transport.connect(getFsConfig().getHost(), getFsConfig().getFromUsername(), getFsConfig().getFromPassword());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            //2.元数据入队列
            EmailMetadata md = new EmailMetadata();
            String address = "";
            for (int i = 0; i < toAddrs.length; i++) {
                address += toAddrs[i];
                address += ",";
            }
            address = address.substring(0, address.length() - 1);
            setMetadataBeanData(metadataInfo, md, RequestType.INSERT.getName(), text);
            md.setToEmailAddrs(address);
            md.setTopic(topic);
            md.setContent(text);
            metadataInQueue(Constants.TOPIC_METADATAINFO, Constants.TYPE_METADATA_EMAIL, md);
            return true;
        } catch (Exception e) {
            //3.异常信息,元数据入redis队列
            handleException(Constants.MODULE_EMAIL, "EmailServiceImpl1", "sendEmailByText", e, logger);
            return false;
        }
    }

    /**
     * @param toAddrs 收件人地址邮箱列表
     * @param topic   邮件主题
     * @param html    邮件内容
     * @return
     */
    @Override
    public boolean sendEmailByHtml(MetadataInfo metadataInfo, String[] toAddrs, String topic, String html) {
        try {
            checkMetadata(metadataInfo);
            //1.发送邮件
            Properties prop = new Properties();
            //prop.setProperty("mail.smtp.auth","true");
            Session session = Session.getInstance(prop, null);
            session.setDebug(false);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(getFsConfig().getFromUsername()));
            message.setContent(html, "text/html; charset=utf-8");
            message.setSubject(topic);

            InternetAddress[] addresses = new InternetAddress[toAddrs.length];
            for (int i = 0; i < toAddrs.length; i++) {
                addresses[i] = new InternetAddress(toAddrs[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addresses);
            Transport transport = session.getTransport("smtp");
            transport.connect(getFsConfig().getHost(), getFsConfig().getFromUsername(), getFsConfig().getFromPassword());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            //2.元数据入队列
            EmailMetadata md = new EmailMetadata();
            String address = "";
            for (int i = 0; i < toAddrs.length; i++) {
                address += toAddrs[i];
                address += ",";
            }
            address = address.substring(0, address.length() - 1);
            setMetadataBeanData(metadataInfo, md, RequestType.INSERT.getName(), html);
            md.setToEmailAddrs(address);
            md.setTopic(topic);
            md.setContent(html);
            metadataInQueue(Constants.TOPIC_METADATAINFO, Constants.TYPE_METADATA_EMAIL, md);
            return true;
        } catch (Exception e) {
            //3.异常信息,元数据入redis队列
            handleException(Constants.MODULE_EMAIL, "EmailServiceImpl1", "sendEmailByHtml", e, logger);
            return false;
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param subject            邮件主题
     * @param sendHtml           邮件内容
     * @param receiveUser        收件人地址邮箱列表
     * @param attachmentDesc     邮件所带附件的说明
     * @param mailAttachmentList 邮件所带附件的列表
     */
    @Override
    public boolean sendAttachmentEmail(MetadataInfo metadataInfo, String subject, String sendHtml, String[] receiveUser, String attachmentDesc, List<MailAttachmentBean> mailAttachmentList) {
        try {
            checkMetadata(metadataInfo);
            //1.发送邮件
            Properties prop = new Properties();
            Session session = Session.getInstance(prop, null);
            session.setDebug(false);
            Message message = new MimeMessage(session);
            // 发送人
            message.setFrom(new InternetAddress(getFsConfig().getFromUsername()));

            // 收件人
            InternetAddress[] addresses = new InternetAddress[receiveUser.length];
            for (int i = 0; i < receiveUser.length; i++) {
                addresses[i] = new InternetAddress(receiveUser[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addresses);
            // 设置发送的主题
            message.setSubject(subject);
            // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            // 添加邮件的正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(sendHtml, "text/html; charset=utf-8");
            multipart.addBodyPart(contentPart);
            // 添加附件的内容
            int len = mailAttachmentList.size();
            for (int i = 0; i < len; i++) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                MailAttachmentBean attachmentBean = mailAttachmentList.get(i);
                //File file = new File(attachmentBean.getFileName() + "." + attachmentBean.getExt());
                //File file = File.createTempFile(attachmentBean.getFileName(),"."+attachmentBean.getExt());
                // 将byte[] 转成file
                byte[] bytes = attachmentBean.getAttachments();
                if (bytes.length == 0) continue;
                //bytes2File(bytes, file);
                //DataSource source = new FileDataSource(file);
                DataSource source1 = new ByteArrayDataSource(bytes,"text/html");
                attachmentBodyPart.setDataHandler(new DataHandler(source1));
                //attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachmentBean.getFileName()+"."+attachmentBean.getExt()));
                multipart.addBodyPart(attachmentBodyPart);
            }
            // 将multipart对象放到message中
            message.setContent(multipart);
            // 保存邮件
            message.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(getFsConfig().getHost(), getFsConfig().getFromUsername(), getFsConfig().getFromPassword());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            //2.元数据入队列
            EmailMetadata md = new EmailMetadata();
            String address = "";
            for (int i = 0; i < receiveUser.length; i++) {
                address += receiveUser[i];
                address += ",";
            }
            address = address.substring(0, address.length() - 1);
            setMetadataBeanData(metadataInfo, md, RequestType.INSERT.getName(), sendHtml);
            md.setToEmailAddrs(address);
            md.setTopic(subject);
            md.setContent(sendHtml);
            md.setAttachmentDesc(attachmentDesc);
            metadataInQueue(Constants.TOPIC_METADATAINFO, Constants.TYPE_METADATA_EMAIL, md);
            return true;
        } catch (Exception e) {
            //3.异常信息,元数据入redis队列
            handleException(Constants.MODULE_EMAIL, "EmailServiceImpl1", "sendAttachmentEmail", e, logger);
            return false;
        }
    }

    // 根据byte[] 生成文件
    public void bytes2File(byte[] bytes, File targetFile) {
        BufferedOutputStream outputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(targetFile);
            outputStream = new BufferedOutputStream(fileOutputStream);
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception e) {
            outputStream = null;
            fileOutputStream = null;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    fileOutputStream = null;
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    outputStream = null;
                }
            }
        }
    }

}
